<?php

namespace app\admin\controller;

use think\Db;
use think\Request;
use think\Exception;//事务处理
use app\admin\model\File;

class Language extends Auth
{
    public function __construct(Request $request){
        $this->getChildIDdata = [];
        parent::__construct($request);
        $this->data = $request->param();
        $this->user_id = session('userid') == null ? 1 : session('userid');
        $this->lang = isset($this->data['lang']) && $this->data['lang'] ? $this->data['lang'] : is_lang();
    }

    // 
    public function list(Request $request)
    {   
        if($request->isAjax()){
            $language = getDatas('language',['*'],'1=1');
            // 获取分页数据
            $returnData['size'] = count( $language);
            if(isset($this->data['page']) && isset($this->data['limit'])){
                if($this->data['limit']*($this->data['page']-1) < $returnData['size']){
                    $language = array_slice($language,$this->data['limit']*($this->data['page']-1),$this->data['limit']);
                    $returnData['page'] = $this->data['page'];;
                }
            }else{
                $returnData['page'] =1;
            }
            foreach ($language as $k => $v) {
                $language[$k]['is_hide'] = $v['status'] == 3 ? 'o' : '-';
            }
            $returnData['language'] = $language;
            $returnData['title'] = lang('language');
            // dump($returnData);die;
            return json_encode($returnData);

        }else{
            return view('list',['request'=>'list','title'=>lang('language')]);
        }
        
    }


    public function addLangType($code){
        // $fileName = $code == 'en' ? 'en' : $code;
        $path = APP_PATH."lang/".$code.".php";
        $res = fopen(APP_PATH."lang/".$code.".php", "w");
        $res1 = fwrite($res,
"<?php
use think\Db;

\$res = Db::name('dict')->field(['abbreviation','content'])->where('lang','".$code."')->select();

\$returnData = array();
\$resCount = count(\$res);
for (\$i=0; \$i < \$resCount; \$i++) { 
    \$returnData[\$res[\$i]['abbreviation']] = \$res[\$i]['content'];
}
// dump(\$returnData);die;
return \$returnData;");

        if($res1){
            return true;
        }else{
            return false;
        }
    }


    public function addopen(Request $request){
        if(isset($this->data['request']) && $this->data['request'] == 'insert'){
            if(isset($this->data['name']) && $this->data['name']) return json_encode(array('status'=>2,'msg'=>lang('missing_name')));
            if(isset($this->data['code']) && $this->data['code']) return json_encode(array('status'=>2,'msg'=>lang('missing').' '.lang('status')));
            if(hasData('language',['name'=>$this->data['name']])) return json_encode(array('status'=>3,'msg'=>lang('language').'->'.$this->data['name'].' '.lang('already_exists')));
            if(hasData('language',['code'=>$this->data['code']])) return json_encode(array('status'=>3,'msg'=>lang('language').'->'.$this->data['code'].' '.lang('already_exists')));
            unset($this->data['request']);
            unset($this->data['old_icon']);
            $this->data['status'] = $this->data['status'] == 'true' ? 3 : 1;
            Db::startTrans();   
            $res = insertData('language',$this->data);
            if($res){
                if($request->file('file')){
                    // 创建新增语言 语言包。
                    $isAddFile = $this->addLangType($this->data['code']);
                    // 增加多语言数据表对应当前添加语音的数据
                    $isAddMultiSQlData = $this->addSqlData($this->data['code']);
                    if($isAddFile && $isAddMultiSQlData){
                        $fileUpdate = new File();
                        $res1 = $fileUpdate->uploadImgs($request->file('file'),'uploads/static/Admin/img/language/',$res,1);
                        if($res1['status'] == 1){
                            Db::commit();
                            $res2 = updateData('language',['id'=>$res],['icon'=>'/'.$res1['filepath']]);
                        }
                        return json_encode(array('status'=>1,'msg'=>lang('language').'->'.$this->data['name'].' '.lang('added_successfully')));
                    }
                }else{
                    // 回滚事务
                    Db::rollback();
                   return json_encode(array('status'=>2,'msg'=>lang('language').'->选择图标'));
                }
            }else{
                return json_encode(array('status'=>0,'msg'=>lang('language').'->'.$this->data['name'].' '.lang('add_failed')));
            }
        }else{
            return view('open',['title'=>lang("add_language_type"),'type'=>'add','request'=>'add']);
        }
    }


    public function editopen(Request $request){
        if(isset($this->data['request']) && $this->data['request'] == 'update'){
            // return $this->data;
            if(isset($this->data['id'])){
                unset($this->data['request']);
                $this->data['status'] = $this->data['status'] == 'true' ? 3 : 1;
                if($request->file('file') != null){
                    $fileUpdate = new File();
                    $res1 = json_decode($fileUpdate->uploadImg($request->file('file'),'uploads/static/Admin/img/language/',$this->data['id']));
                    // return $res1;
                    if($res1->code == 2000){
                        $this->data['icon'] = '/'.$res1->filepath;
                    }
                }

                if(file_exists(ROOT_PATH . 'public' . DS . $this->data['icon'])){
                    if(file_exists(ROOT_PATH . 'public' . DS . $this->data['old_icon'])){
                        $r = unlink(ROOT_PATH . 'public' . DS . $this->data['old_icon']); 
                    }
                }else{
                    $this->data['icon'] = $this->data['old_icon'];
                }
                unset($this->data['old_icon']);
                // return $this->data;
                $res = updateData('language',['id'=>$this->data['id']],$this->data);
                if($res >=0){
                    return json_encode(array('status'=>1,'msg'=>lang('language').'->'.getValue('language',['id'=>$this->data['id']],['name']).' '.lang('edited_successfully')));
                }else{
                    return json_encode(array('status'=>0,'msg'=>lang('language').'->'.getValue('language',['id'=>$this->data['id']],['name']).' '.lang('edit_failed')));
                }
            }
            
        }else{

            $language = getDatas('language',['*'],['id'=>$this->data['id']])[0];
            // return $language;
            return view('open',['title'=>lang("edit_language_type"),'type'=>'edit','id'=>$this->data['id'],'request'=>'edit','language'=>$language]);
            
            
        }
    }

    public function changeStatus(){
        // return $this->data;
        if($this->data['id']){
            $res = updateData('language',['id'=>$this->data['id']],['status'=>$this->data['status']]);
            if($res){
                return json_encode(array('status'=>1,'msg'=>lang('language').'->'.getValue('language',['id'=>$this->data['id']],['name']).' '.lang(getViewMultiLanguage($this->data['status'])).' '.lang('successfully')));
            }else{
                return json_encode(array('status'=>0,'msg'=>lang('language').'->'.getValue('language',['id'=>$this->data['id']],['name']).' '.lang(getViewMultiLanguage($this->data['status'])).' '.lang('failed')));
            }
        }else{
            return json_encode(array('status'=>2,'msg'=>'miss_requsrtData'));
        }
    }

    public function delete(){
        if($this->data['id']){
            $language = Db::name('language')->where(['id'=>$this->data['id']])->find();
            $res = deleteData('language',['id'=>$this->data['id']]);
            if($res){
                unlink(APP_PATH.'lang/'.$language['code'].'.php');
                return json_encode(array('status'=>1,'msg'=>lang('language').'->'.$language['name'].' '.lang('cleared_successfully')));
            }else{
                return json_encode(array('status'=>0,'msg'=>lang('language').'->'.$language['name'].' '.lang('clear_failed')));
            }
        }else{
            return json_encode(array('status'=>2,'msg'=>'improve_submission_data'));
        }
    }


    public function ImgUpdate(Request $request){
        if ($request->isPost()) {
            $fileUpdate = new File();
            $res = $fileUpdate->uploadImg($request->file('file'),'static/Admin/img/language/');
            return $res;
        }
    }


    public function addSqlData($code)
    {
        $dictData = Db::name('dict')->field(['abbreviation','content'])->where('lang',$this->lang)->select();
        foreach ($dictData as $k => $v) {
            $v['lang'] = $code;
            $res = insertData('dict',$v);
        }

        $multi_langData = Db::name('multi_lang')->field(['mkey','content'])->where('lang',$this->lang)->select();
        foreach ($multi_langData as $k1 => $v1) {
            $v1['lang'] = $code;
            $v1['content'] = $v1['content'].'_'.$code;
            $res1 = insertData('multi_lang',$v1);
        }
        if($res && $res1){
            return true;
        }else{
            return false;
        }
    }

}